package com.bwie.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.mapper.*;
import com.bwie.poi.ExcelUtil;
import com.bwie.pojo.*;
import com.bwie.service.OrderService;
import com.bwie.utils.R;
import com.bwie.vo.OrderPageVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 陶仕豪
 * @description 针对表【tb_order(订单表)】的数据库操作Service实现
 * @createDate 2025-07-23 14:09:36
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order>
        implements OrderService {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    HttpServletResponse response;

    @Autowired
    HttpServletRequest request;
    @Autowired
    ProdInfoMapper prodInfoMapper;
    @Autowired
    ProdMapper prodMapper;
    @Autowired
    OrderRecordMapper orderRecordMapper;
    @Override
    public R getOrderList(OrderPageVo orderPageVo) {
        Page<Order> orderPage = new Page<>(orderPageVo.getPageNum(), orderPageVo.getPageSize());
        Page<Order> page = orderMapper.getOrderList(orderPage, orderPageVo);

        for (Order record : page.getRecords()) {
            ArrayList<String> list = new ArrayList<>();
            List<String> images = orderMapper.selectImages(record.getOrderId());
            if (images.size() > 0 && images != null) {
                for (String image : images) {
                    if (image != null) {
                        List<String> strings = JSON.parseArray(image, String.class);
                        list.addAll(strings);
                    }
                }
            }
            record.setImageList(list);
        }

        return R.OK(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R deleteAllOrder(List<Order> orderList) {
        if (orderList == null || orderList.size() == 0) {
            return R.ERROR(500, "请选择需要删除的订单");
        }
        //循环删除订单
        for (Order order : orderList) {
            orderDetailMapper.delete(new QueryWrapper<OrderDetail>().lambda().eq(OrderDetail::getOrderId, order.getOrderId()));
            orderMapper.deleteById(order.getOrderId());


        }
        return R.OK();
    }

    @Override
    public void exportOrder(String ids) {
        String[] split = ids.split(",");
        ArrayList<Integer> integers = new ArrayList<>();
        for (String id : split) {
            integers.add(Integer.parseInt(id));
        }
        //查询订单列表
        List<Order> orders = orderMapper.selectBatchIds(integers);
        //导出文件
        ExcelUtil<Order> excelUtil = new ExcelUtil<>(Order.class);
        excelUtil.exportExcel(response,orders,"订单列表");

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public R addOrder(List<ProdInfo> prodInfoList) {

        String token = request.getHeader("token");
        if (token == null) {
            return R.ERROR(500, "请先登录");
        }
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        String userName = body.get("userName", String.class);
        Integer userId = body.get("userId", Integer.class);

        BigDecimal amount = new BigDecimal(0.0);
        StringBuilder nameList = new StringBuilder();//可变字符串

        for (ProdInfo tbProdInfo : prodInfoList) {
            ProdInfo prodInfo = prodInfoMapper.selectById(tbProdInfo.getProdId());
            if(tbProdInfo.getBuyNum()>prodInfo.getProdStock()){
                return R.ERROR(500,"库存不足");
            }else{
                prodInfo.setProdStock(prodInfo.getProdStock()-tbProdInfo.getBuyNum());
                prodInfoMapper.updateById(prodInfo);
            }
            //计算金额
            amount=prodInfo.getProdPrice().multiply(new BigDecimal(tbProdInfo.getBuyNum())).add(amount);
            //拼接名称
          if(nameList.length()>0){
              nameList.append(",");
          }
             nameList.append(prodInfo.getProdName());
        }




        Order order = new Order();
        order.setOrderNo(IdUtil.getSnowflake(1,1).nextId());
        order.setOrderStatus(0);
        order.setOrderType(1);
        order.setUserId(userId);
        order.setCreateBy(userName);
        order.setCreateTime(new Date());
        order.setOrderAmount(amount);
        order.setPayTime(null);
        order.setProdInfo(nameList.toString());
        orderMapper.insert(order);

        for (ProdInfo prodInfo : prodInfoList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(order.getOrderId());
            orderDetail.setProdId(prodInfo.getProdId());
            orderDetail.setInfoId(prodInfo.getInfoId());
            orderDetail.setBuyNum(prodInfo.getBuyNum());
            orderDetail.setBuyPrice(prodInfo.getProdPrice());
            orderDetail.setCreateBy(userName);
            orderDetail.setCreateTime(new Date());
            orderDetailMapper.insert(orderDetail);
        }
        //订单记录
        OrderRecord orderRecord = new OrderRecord();
        orderRecord.setCreateTime(new Date());
        orderRecord.setCreateBy(userName);
        orderRecord.setOrderId(order.getOrderId());
        orderRecord.setOptRecord("用户添加订单");
        orderRecordMapper.insert(orderRecord);
        return R.OK();
    }

    @Override
    public R getOrderRecordList() {
        QueryWrapper<OrderRecord> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(OrderRecord::getCreateTime);
        List<OrderRecord> orderRecordList = orderRecordMapper.selectList(wrapper);
        return R.OK(orderRecordList);
    }
}




